package com.example.demo.config.service.serviceImpl;

import com.example.demo.dto.LoginUser;
import com.example.demo.entity.Auth;
import com.example.demo.entity.Role;
import com.example.demo.mapper.AuthMapper;
import com.example.demo.mapper.RoleMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.utils.CheckUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;



/**
 * 用户账号 密码 角色 权限 验证
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private AuthMapper authMapper;


    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if(username == null || "".equals(username)){
           throw new UsernameNotFoundException("账号不允许为空");
        }

        System.out.println(username);
        //查询出密码
        com.example.demo.entity.User user = userMapper.selectById(username);

        if(CheckUtil.checkObject(user)){
            throw new UsernameNotFoundException("账号不存在");
        }
        //查询所有的角色信息
        List<Role> allRolesByUserId = roleMapper.getAllRolesByUserId(username);

        if(CheckUtil.checkObject(allRolesByUserId)){
            throw new UsernameNotFoundException("无角色信息");
        }
        Set<GrantedAuthority> authorities = new HashSet<>();
        //查询该角色拥有的权限
        allRolesByUserId.forEach((m)->{
            List<Auth> allAuthByRoleId = authMapper.getAllAuthByRoleId(m.getRoleId());

            if(CheckUtil.checkObject(allAuthByRoleId)){
                throw new UsernameNotFoundException("无权限信息");
            }
            allAuthByRoleId.forEach((n)->{
                SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(m.getRoleName()+":"+n.getAuthName());
                authorities.add(simpleGrantedAuthority);
            });
        });
        return new LoginUser(username, user.getUserPassword(), authorities);
    }
}
